package cn.kwq.project_manger.service.impl;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.IdUtil;
import cn.kwq.project_manger.config.MinioConfig;
import cn.kwq.project_manger.pojo.Files;
import cn.kwq.project_manger.pojo.QFiles;
import cn.kwq.project_manger.pojo.QProject;
import cn.kwq.project_manger.repostitory.FilesRepository;
import cn.kwq.project_manger.repostitory.ProjectRepository;
import cn.kwq.project_manger.service.FilesService;
import cn.kwq.project_manger.utils.MinioUtil;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FilesServiceImpl implements FilesService {

    @Autowired
    MinioUtil minioTemplate;

    @Autowired
    FilesRepository filesRepository;

    @Autowired
    MinioConfig minioConfig;

    @Autowired
    JPAQueryFactory jpaQueryFactory;





    @Override
    @Transactional
    public String uploadImage(MultipartFile file,long id) throws Exception {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
            // 得到文件流
            InputStream stream = file.getInputStream();
            // 原始文件名
            String fileName = file.getOriginalFilename();
            //后缀名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            //为该文件生成唯一的uuid
            String UUID = IdUtil.simpleUUID();

            //生成新文件名
            String newFileName =UUID+"."+suffix;


            //DONE:  2022/11/13 22:41 桶名
            String bucketName="test";
            // 把文件放到minio的桶里面
            minioTemplate.putImageObject(bucketName,newFileName,stream,suffix);
            // 关闭输入流
            stream.close();

            String fileUrl=minioConfig.getUrl()+"/"+bucketName+"/"+newFileName;

            QFiles f=QFiles.files;
        Long fileId = jpaQueryFactory
                .select(f.fileId)
                .from(f)
                .where(f.userId.eq(id))
                .fetchOne();

        //如果url更新了，那么删除原来s3的文件(这样就不会冗余)
        String oldUrl = jpaQueryFactory
                .select(f.url)
                .from(f)
                .where(f.userId.eq(id))
                .fetchOne();

        if (oldUrl.equals(fileUrl)){
            return oldUrl;
        }else {
            minioTemplate.delImageObject(oldUrl);
        }

        //存入或更新数据库
        filesRepository.save(Files
                .builder()
                        .fileId(fileId)
                        .url(fileUrl)
                        .userId(id)
                        .fileUUID(UUID)
                        .type(1)
                        .suffix(suffix)
                        .fileName(fileName)
                .build());



        return fileUrl;
    }

    @Override
    @Transactional
    public String addProJImage(MultipartFile file, long userId,long projectId) {
        // 原始文件名
        String fileName = file.getOriginalFilename();
        //后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //为该文件生成唯一的uuid
        String UUID = IdUtil.simpleUUID();

        // TODO: 2022/11/16 注意更改桶名字
        String imageUrl = minioTemplate.putOBJ("test", UUID, file, suffix);

        //更新到文件表
        //存入或更新数据库
        filesRepository.save(Files
                .builder()
                .url(imageUrl)
                .userId(userId)
                .fileUUID(UUID)
                .type(2)
                .suffix(suffix)
                .fileName(fileName)
                .projectId(projectId)
                .build());

        return imageUrl;
    }

    @Override
    @Transactional
    public void delImage(String url,long projectId) {
        minioTemplate.delImageObject(url);//执行删除

        //删除数据库记录
        //删除文件表
        QFiles files=QFiles.files;
        jpaQueryFactory.delete(files)
                .where(files.url.eq(url))
                .execute();

    }

    @Override
    @SaIgnore
    public List<String> getImgUrlByProJId(long projectId) throws Exception {
        QFiles file=QFiles.files;
        List<Files> fetch = jpaQueryFactory.select(file)
                .from(file)
                .where(file.projectId.eq(projectId))
                .fetch();
        if (fetch==null||(fetch.isEmpty()||fetch.get(0)==null)){
            return null;
        }
        //拦截图片格式
        return fetch
                .stream()
                .filter(item-> isImage(item.getSuffix()))
                .map(Files::getUrl)
                .collect(Collectors.toList());
    }


    public boolean isImage(String suffix){
        return switch (suffix) {
            case "jpg",
                    "bmp",
                    "JPG",
                    "jpeg",
                    "JPEG",
                    "png",
                    "PNG",
                    "gif",
                    "GIF",
                    "raw",
                    "RAW",
                    "heic",
                    "HEIC",
                    "tif",
                    "dng",
                    "DNG",
                    "xbm",
                    "pjp",
                    "svgz",
                    "ico",
                    "tiff",
                    "svg",
                    "jfif",
                    "webp",
                    "pjpeg",
                    "avif"
                    -> true;
            default -> false;
        };
    }


}
